package me.numark.fragments;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import me.numark.R;
import me.numark.model.Feed;
import me.numark.model.FeedListResponse;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.Settings;
import me.numark.view.FeedSimpleAdapter;
import me.numark.view.FeedViewHolder;

/**
 * Created by Evan on 15/7/24.
 */
public class FeedFragment extends BaseListFragment {

    private static final String ARG_TYPE = "type";
    private static final String ARG_USERID = "userid";
    private static final String ARG_TAG = "tag";
    private int feedType;
    private int mUserId;
    private String tag;

    FeedSimpleAdapter mFeedAdapter;
    boolean isPrivate;

    public static FeedFragment newInstance(int feedType, int mUserId) {
        FeedFragment fragment = new FeedFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_TYPE, feedType);
        args.putInt(ARG_USERID, mUserId);
        fragment.setArguments(args);
        return fragment;
    }

    public static FeedFragment newInstance(int feedType, String tag) {
        FeedFragment fragment = new FeedFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_TYPE, feedType);
        args.putString(ARG_TAG, tag);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            feedType = getArguments().getInt(ARG_TYPE, Constants.FEEDTYPE_TIMELINE);
            mUserId = getArguments().getInt(ARG_USERID, Global.getCurrentUid());
            tag = getArguments().getString(ARG_TAG, null);
        }
        if (feedType == Constants.FEEDTYPE_TIMELINE) {
            needLogin = true;
        }
        dataList = new ArrayList();
        mFeedAdapter = new FeedSimpleAdapter(this, dataList, feedType);
        mAdapter = mFeedAdapter;
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mFeedFragmentReceiver,
                new IntentFilter(Constants.ACTION_FEED_DELETED));
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver,
                new IntentFilter(Constants.NOTIFY));
    }

    @Override
    public void onDestroy() {
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mFeedFragmentReceiver);
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
        super.onDestroy();

    }

    @Override
    public void initUI(View view) {
        super.initUI(view);
        titleTextView.setText(R.string.timeline);
        if (feedType == Constants.FEEDTYPE_TAG_HOT
                || feedType == Constants.FEEDTYPE_TAG_LAST
                || feedType == Constants.FEEDTYPE_SEARCH_FOLLOW
                || feedType == Constants.FEEDTYPE_SEARCH_ALL
                ) {
            toolbar.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadMore(int itemsCount, int maxLastVisiblePosition) {
        super.loadMore(itemsCount, maxLastVisiblePosition);
        loadData(itemsCount);
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        loadData(0);
    }

    protected String getFeedUrl() {
        switch (feedType) {
            case Constants.FEEDTYPE_TIMELINE:
                return String.format(NetworkConstants.NEWS_TIMELINE_URL, Global.getCurrentUid());
            case Constants.FEEDTYPE_LAST_MARK:
                return String.format(NetworkConstants.LAST_MARK_URL, Global.getCurrentUid());
            case Constants.FEEDTYPE_TAG_LAST:
            case Constants.FEEDTYPE_TAG_HOT:
                return String.format(NetworkConstants.NEWS_BY_TYPE);
            case Constants.FEEDTYPE_USER_MARKS:
                /*//TODO 修改URL
                return String.format(NetworkConstants.PROFILE_MARK_URL, mUserId);*/
                return String.format(NetworkConstants.MINE_MARKS, mUserId);
            case Constants.FEEDTYPE_USER_COMMENTS:
                return String.format(NetworkConstants.PROFILE_COMMENT_URL, mUserId);
            case Constants.FEEDTYPE_USER_LIKES:
                /*//TODO 修改URL
                return String.format(NetworkConstants.PROFILE_LIKE_URL, mUserId);*/
                return String.format(NetworkConstants.MINE_LIKES, mUserId);
            case Constants.FEEDTYPE_SEARCH_ALL:
            case Constants.FEEDTYPE_SEARCH_FOLLOW:
                return String.format(NetworkConstants.SEARCH_URL, Global.getCurrentUid());
            default:
                return null;
        }
    }

    @Override
    protected String cacheKey() {
        return "feed_" + feedType + "_" + mUserId + "_" + tag;
    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, FeedListResponse.class);
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        FeedListResponse resp = (FeedListResponse) response;
        if (isNew) {
            mFeedAdapter.clear();
        }
        mFeedAdapter.append(resp.data);
        setHasMore(resp.has_more);
    }

    protected void loadData(final int start) {
        if (needLogin && Global.currentUser == null) {
            endRefreshing();
            showEmptyView();
            return;
        }
        new RequestServerTask<FeedListResponse>(FeedListResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                Map<String, Object> postParams = new HashMap<String, Object>();
                params.put("start", String.valueOf(start));
                params.put("limit", String.valueOf(Constants.PAGE_SIZE));
                if (feedType == Constants.FEEDTYPE_TIMELINE){

                    Long feedMaxMid = Global.currentMaxMid;

                    if (feedMaxMid == 0){
                        feedMaxMid = Settings.getFeedMaxMid();
                    }
                    if (feedMaxMid != 0) {
                        postParams.put("maxid", feedMaxMid);
                    }
                } else if (feedType == Constants.FEEDTYPE_TAG_HOT) {
                    params.put("type", tag);
                } else if (feedType == Constants.FEEDTYPE_TAG_LAST) {
                    params.put("type", tag);
                }
                if (feedType == Constants.FEEDTYPE_SEARCH_ALL) {
                    params.put("text", searchKey);
                    params.put("type", "total");
                } else if (feedType == Constants.FEEDTYPE_SEARCH_FOLLOW) {
                    params.put("text", searchKey);
                    params.put("type", "topic");
                }
                if (start > 0 && lastResponseTime > 0) {
                    params.put("time", String.valueOf(lastResponseTime));
                }
                return HttpUtil.post(getFeedUrl(), params, postParams, null);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            private Handler mHandler = new Handler(){
                @Override
                public void handleMessage(android.os.Message msg)
                {
                    if(msg.what == 98)
                    {
                        updateMsg.setText("");
                        updateMsg.setVisibility(View.GONE);

                    }
                }
            };

            @Override
            protected void onSuccess(FeedListResponse result) {
                if (feedType == Constants.FEEDTYPE_TAG_HOT) {
                    bindData(result, start == 0);
                }else {
                    bindData(result,start==0);
                }
                if (feedType == Constants.FEEDTYPE_TIMELINE){
                    if (updateMsg != null){
                        int new_num = result.new_num;
                        if (new_num != 0) {
                            updateMsg.setVisibility(View.VISIBLE);
                            String data = getResources().getString(R.string.update_num_msg);
                            updateMsg.setText(String.format(data,new_num));
                            Animator animator = AnimatorInflater.loadAnimator(getActivity(), R.animator.update_msg_anim);
                            animator.setTarget(updateMsg);
                            animator.start();
                            mHandler.sendEmptyMessageDelayed(98, 3000);
                        }
                    }
                    int unRead = result.unread_msg;
                    if (unRead > 0){
                        LocalBroadcastManager.getInstance(FeedFragment.this.getActivity())
                                .sendBroadcast(new Intent(Constants.ACTION_HAS_UNREAD));
                    }
                }
            }
        }
                .setSnackbarView(rootView)
                .start();
    }

    BroadcastReceiver mFeedFragmentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.ACTION_FEED_DELETED.equals(intent.getAction())) {
                long mid = intent.getLongExtra(Constants.FEED_MID_EXTRA, 0);
                if (mid != 0) {
                    for (int i = 0; i < dataList.size(); i++) {
                        Feed feed = (Feed) dataList.get(i);
                        if (feed.id == mid) {
                            mAdapter.remove(dataList, i);
                            break;
                        }
                    }
                }
            }
        }
    };

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.NOTIFY.equals(intent.getAction())){
                //TODO 更新指定条目状态
               /* Feed feed = new Gson().fromJson(intent.getStringExtra(Constants.NOTIFY_ACTION), Feed.class);
                int size = dataList.size();
                for (int i = 0;i<dataList.size();i++){
                    if (feed.id == ((Feed)dataList.get(i)).id){
                        dataList.set(i,feed);
                    }
                }
                mFeedAdapter.notifyDataSetChanged();*/
                Feed feed = new Gson().fromJson(intent.getStringExtra(Constants.NOTIFY_ACTION), Feed.class);
                if (feedType == Constants.FEEDTYPE_TIMELINE){
                    boolean cotain = false;
                    if (feed.addFeedTag !=null){

                        for (int i = 0; i < dataList.size(); i++) {
                            Feed f = (Feed)dataList.get(i);
                            if (feed.id== f.id && feed.news.id == f.news.id){
                                f.labels.add(0,feed.addFeedTag);
                                f.label_num++;
                                if (f.labels.size()==11){
                                    f.labels.remove(f.labels.size()-1);
                                }
                                cotain = true;
                            }
                        }
                        if (!cotain){
                            refresh();
                        }
                    }

                    if (feed.deleteFeedTag != null){
                        for (int i = 0; i <dataList.size() ; i++) {
                            Feed f = (Feed)dataList.get(i);
                            if (feed.id == f.id && feed.news.id == f.news.id){
                                f.label_num--;
                                for (int j = 0;j<f.labels.size(); j++) {
                                    if (feed.deleteFeedTag.id == f.labels.get(j).id){
                                        f.labels.remove(j);
                                    }
                                }

                            }
                        }
                    }

                    if (feed.updateFeedTag!=null){
                        for (int i = 0; i <dataList.size() ; i++) {
                            Feed f = (Feed)dataList.get(i);
                            if (feed.id == f.id && feed.news.id == f.news.id){
                                for (int j = 0;j<f.labels.size(); j++) {
                                    if (feed.updateFeedTag.id == f.labels.get(j).id){
                                        f.labels.set(j,feed.updateFeedTag);
                                    }
                                }

                            }
                        }
                    }
                    mFeedAdapter.notifyDataSetChanged();
                }
                if (feedType == Constants.FEEDTYPE_TAG_HOT){
                    boolean cotain = false;
                    if (feed.addFeedTag !=null){
                        for (int i = 0; i < dataList.size(); i++) {
                            Feed f = (Feed)dataList.get(i);
                            if (feed.news.id == f.news.id){
                                f.labels.add(0,feed.addFeedTag);
                                f.news.label_num++;
                                if (f.labels.size()==11){
                                    f.labels.remove(10);

                                }
                                cotain = true;
                            }
                        }
                        if (!cotain){
                            refresh();
                        }
                    }

                    if (feed.deleteFeedTag != null){
                        for (int i = 0; i <dataList.size() ; i++) {
                            Feed f = (Feed)dataList.get(i);
                            if (feed.news.id == f.news.id){
                                for (int j = 0;j<f.labels.size(); j++) {
                                    if (feed.deleteFeedTag.id == f.labels.get(j).id){
                                        f.labels.remove(j);
                                        f.news.label_num--;
                                    }
                                }
                            }
                        }
                    }

                    if (feed.updateFeedTag!=null){
                        for (int i = 0; i <dataList.size() ; i++) {
                            Feed f = (Feed)dataList.get(i);
                            if (feed.news.id == f.news.id){
                                for (int j = 0;j<f.labels.size(); j++) {
                                    if (feed.updateFeedTag.id == f.labels.get(j).id){
                                        f.labels.set(j,feed.updateFeedTag);
                                    }
                                }
                            }
                        }
                    }
                    mFeedAdapter.notifyDataSetChanged();
                }
            }
        }
    };
}
